package com.gitee.peigenlpy.actable.utils;

import org.noear.solon.core.AppClassLoader;
import org.noear.solon.core.util.ClassUtil;
import org.noear.solon.core.util.ScanUtil;

import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;

@SuppressWarnings("unchecked")
public class ClassScanner {
    private ClassLoader classLoader;

    public Set<Class<?>> scan(String[] basePackages, Class<? extends Annotation>... annotations) {
        getClassLoader();
        Set<Class<?>> scanClass = new HashSet<>();

        Arrays.stream(basePackages).forEach(basePackage -> {
            String dir = basePackage.replace('.', '/');
            ScanUtil.scan(getClassLoader(), dir, n -> n.endsWith(".class"))
                    .stream()
                    // .filter()
                    .sorted(Comparator.comparing(String::length))
                    .forEach(name -> {
                        String className = name.substring(0, name.length() - 6);
                        className = className.replace("/", ".");

                        Class<?> clz = ClassUtil.loadClass(classLoader, className);
                        if (clz != null) {
                            scanClass.add(clz);
                        }
                    });
        });

        return scanClass;
    }

    public ClassLoader getClassLoader() {
        if (classLoader == null) {
            return AppClassLoader.global();
        } else {
            return classLoader;
        }
    }

}
